package com.learn.collection.demo;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能：List 与 String 相互转化
 *
 * @author wsh
 * @date 2020/9/15
 */
public class ListAndString {
    /**
     * 功能：List<String> 转换为以分隔符 separator 相连的 String
     *
     * @param list      待转换的 List
     * @param separator 分隔符
     * @return 以分隔符 separator 相连的 String
     * @author wsh
     * @date 2020/4/21
     */
    public static String listToString1(List<String> list, String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)).append(separator);
        }
        return list.isEmpty() ? "" : sb.toString().substring(0, sb.toString().length() - 1);
    }

    public static String listToString2(List<String> list, String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                sb.append(list.get(i));
            } else {
                sb.append(list.get(i));
                sb.append(separator);
            }
        }
        return sb.toString();
    }

    public static String listToString3(List<String> list, String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
            if (i < list.size() - 1) {
                sb.append(separator);
            }
        }
        return sb.toString();
    }

    /**
     * 功能：List<String> 转化为 String
     * listToString1、listToString2、listToString3 是同一种思路，listToString4 效果相同，书写更方便
     *
     * @param list
     * @param separator
     * @return
     * @author wsh
     * @date 2020/9/15
     */
    public static String listToString4(List<String> list, String separator) {
        return StringUtils.join(list.toArray(), separator);
    }

    public static void main(String[] args) {
        System.out.println("********** 测试 List<String> -> String Begin **********");
        List<String> list = new ArrayList<>();
        list.add("苹果");
        list.add("香蕉");
        list.add("橘子");
        list.add("西瓜");
        System.out.println(listToString1(list, ","));
        System.out.println(listToString2(list, ","));
        System.out.println(listToString3(list, ","));
        System.out.println(listToString4(list, ","));
        System.out.println("********** 测试 List<String> -> String End **********");
    }
}
